package exam;

import java.util.ArrayList;
import java.util.List;

public class Generate {
    //保存已经抽选了的学生
    private List<String> hasAnswered=new ArrayList<>();
    //保存以及抽选了的题目
    private List<Problem> hasUsed=new ArrayList<>();

    private LoadResource loadResource=LoadResource.getInstance();

    //读取已经加载到内存中的题
    private List<Problem> problems = loadResource.loadProblems();

    /**
     * 随机产生一道题，如果所有的题都已经被抽了一遍，则从新开始抽题
     * @return
     */
    public Problem random_problem(){
        while (true){
            //产生0~problems.size()-1 之间的随机对象
            int index= (int) (Math.random()* problems.size());
            //随机获取problem对象
            Problem problem = problems.get(index);
            if (! hasUsed.contains(problem)){
                hasUsed.add(problem);
                if (hasUsed.size()==problems.size()){
                    hasUsed.clear();
                }
                return problem;
            }
        }
    }

    public String random_student(){
        //读取已经加载到内存中的学生
        List<String> list = loadResource.loadStudents();
        while (true){
            //产生0~list.size()-1 之间的随机对象
            int index= (int) (Math.random()*list.size());
            //随机获取学生对象
            String s = list.get(index);
            if (! hasAnswered.contains(s)){
                hasAnswered.add(s);
                if (hasAnswered.size()==list.size()){
                    hasAnswered.clear();
                }
                return s;
            }
        }
    }

    /**
     * 生成人和题
     * @param count
     * @return
     */
    public Problem[] generate(int count){
        if (count>this.problems.size()-this.hasUsed.size()){
            count=this.problems.size()-this.hasUsed.size();
        }
        Problem[] problems=new Problem[count];
        for (int i=0;i< problems.length;i++){
            //随机生成count道题
            Problem problem=this.random_problem();
            problems[i]=problem;
        }
        return problems;
    }
}
